<template>
  <div class="kitchen-center-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-icon class="header-icon"><Dish /></el-icon>
      <h2 class="header-title">出餐中心</h2>
      <div class="header-info">
        <el-tag type="info" size="large">待出餐订单：{{ totalOrders }} 个</el-tag>
        <el-tag type="warning" size="large" style="margin-left: 10px">待出餐菜品：{{ totalItems }} 项</el-tag>
      </div>
      <div class="header-actions">
        <el-button
          type="warning"
          @click="showQuickPlan"
          :disabled="expandedOrders.length === 0"
          class="plan-btn"
        >
          <el-icon><DataAnalysis /></el-icon>
          快速规划
        </el-button>
        <el-button
          :type="sortByTime ? 'success' : 'info'"
          @click="toggleSortByTime"
          class="sort-btn"
        >
          <el-icon><Sort /></el-icon>
          {{ sortByTime ? '时间排序' : '默认排序' }}
        </el-button>
        <el-button type="primary" icon="Refresh" @click="refreshData" circle class="refresh-btn"></el-button>
      </div>
    </div>

    <!-- 展开的订单卡片区域 -->
    <div class="expanded-orders-section">
      <div v-if="expandedOrders.length === 0" class="empty-state">
        <el-icon class="empty-icon"><CircleCheck /></el-icon>
        <p>暂无待出餐订单</p>
      </div>
      <el-row :gutter="20" v-else>
        <el-col
          v-for="(order, index) in expandedOrders"
          :key="order.order_id"
          :xs="24"
          :sm="12"
          :md="12"
          :lg="6"
          draggable="true"
          @dragstart="handleDragStart(index, $event)"
          @dragover.prevent="handleDragOver(index, $event)"
          @dragend="handleDragEnd"
          @drop="handleDrop(index, $event)"
          class="draggable-col"
        >
          <el-card class="order-card" shadow="hover">
            <template #header>
              <div class="order-card-header">
                <div class="order-info">
                  <el-tag type="primary" size="large">{{ order.table_number }}</el-tag>
                  <span class="order-number">{{ order.order_number }}</span>
                </div>
                <div class="order-meta">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatTimeInMinutes(order.latest_item_time) }}</span>
                </div>
              </div>
            </template>
            <div class="order-items">
              <div v-for="item in order.items" :key="item.id" class="menu-item">
                <div class="menu-item-info">
                  <span class="menu-name">{{ item.menu_name }}</span>
                  <el-tag
                    :type="getCategoryTypeColor(item.category_type)"
                    size="small"
                  >
                    {{ item.category_type }}
                  </el-tag>
                  <el-tag type="warning" size="small">x{{ item.quantity }}</el-tag>
                </div>
                <div class="menu-item-time">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatTimeInMinutes(item.create_time) }}</span>
                </div>
                <el-button
                  type="success"
                  size="small"
                  @click="markAsServed(item.id, order.order_id)"
                  class="serve-btn"
                >
                  <el-icon><Check /></el-icon>
                  已出餐
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 折叠的订单列表 -->
    <div class="collapsed-orders-section" v-if="collapsedOrders.length > 0">
      <el-divider content-position="left">
        <span class="divider-text">更多订单（点击展开）</span>
      </el-divider>
      <div class="collapsed-orders-list">
        <div
          v-for="order in collapsedOrders"
          :key="order.order_id"
          class="collapsed-order-item"
        >
          <div class="collapsed-order-info" @click="expandOrderToCard(order.order_id)">
            <el-tag type="primary">{{ order.table_number }}</el-tag>
            <span class="order-number">{{ order.order_number }}</span>
            <el-tag type="warning" size="small">{{ order.pending_count }} 项待出餐</el-tag>
          </div>
          <div class="collapsed-order-time">
            <el-icon><Clock /></el-icon>
            <span>{{ formatTimeInMinutes(order.latest_item_time) }}</span>
          </div>
          <div class="collapsed-order-actions">
            <el-tooltip content="在卡片中显示" placement="top">
              <el-button
                type="primary"
                size="small"
                circle
                @click="expandOrderToCard(order.order_id)"
              >
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="弹窗查看" placement="top">
              <el-button
                type="info"
                size="small"
                circle
                @click="showOrderDialog(order.order_id)"
              >
                <el-icon><View /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="orderDialogVisible"
      :title="`订单详情 - ${currentDialogOrder?.table_number || ''}`"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="currentDialogOrder" class="order-dialog-content">
        <div class="order-dialog-header">
          <div class="order-dialog-info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">{{ currentDialogOrder.order_number }}</el-descriptions-item>
              <el-descriptions-item label="餐台号">{{ currentDialogOrder.table_number }}</el-descriptions-item>
              <el-descriptions-item label="开台时间" :span="2">
                {{ formatFullTime(currentDialogOrder.open_time) }}
              </el-descriptions-item>
              <el-descriptions-item label="待出餐数量" :span="2">
                <el-tag type="warning" size="large">{{ currentDialogOrder.pending_count }} 项</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <el-divider content-position="left">菜品明细</el-divider>

        <div class="order-dialog-items">
          <div v-for="item in currentDialogOrder.items" :key="item.id" class="dialog-menu-item">
            <div class="dialog-menu-item-info">
              <span class="dialog-menu-name">{{ item.menu_name }}</span>
              <el-tag
                :type="getCategoryTypeColor(item.category_type)"
                size="small"
              >
                {{ item.category_type }}
              </el-tag>
              <el-tag type="warning" size="small">x{{ item.quantity }}</el-tag>
            </div>
            <div class="dialog-menu-item-time">
              <el-icon><Clock /></el-icon>
              <span>{{ formatTimeInMinutes(item.create_time) }}</span>
            </div>
            <el-button
              type="success"
              size="small"
              @click="markAsServedFromDialog(item.id)"
              class="dialog-serve-btn"
            >
              <el-icon><Check /></el-icon>
              已出餐
            </el-button>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="orderDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="expandOrderToCardFromDialog">
          <el-icon><ArrowRight /></el-icon>
          在卡片中显示
        </el-button>
      </template>
    </el-dialog>

    <!-- 快速规划对话框 -->
    <el-dialog
      v-model="planDialogVisible"
      title="快速规划 - 菜品汇总"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="plan-dialog-content">
        <!-- 统计信息 -->
        <div class="plan-summary">
          <el-alert type="info" :closable="false" show-icon>
            <template #title>
              <span style="font-size: 16px; font-weight: 600;">
                当前展开 {{ expandedOrders.length }} 个订单，共需准备 {{ planSummary.totalItems }} 项菜品
              </span>
            </template>
          </el-alert>
        </div>

        <!-- 按餐品类型分组显示 -->
        <el-tabs v-model="activeTab" class="plan-tabs">
          <!-- 全部菜品 -->
          <el-tab-pane label="全部菜品" name="all">
            <div class="plan-list">
              <div v-if="planSummary.allItems.length === 0" class="empty-plan">
                <el-empty description="暂无菜品数据" />
              </div>
              <div v-else>
                <div
                  v-for="(item, index) in planSummary.allItems"
                  :key="index"
                  class="plan-item"
                >
                  <div class="plan-item-rank">{{ index + 1 }}</div>
                  <div class="plan-item-info">
                    <span class="plan-item-name">{{ item.menuName }}</span>
                    <el-tag
                      :type="getCategoryTypeColor(item.categoryType)"
                      size="small"
                    >
                      {{ item.categoryType }}
                    </el-tag>
                  </div>
                  <div class="plan-item-quantity">
                    <el-tag type="danger" size="large" effect="dark">
                      x{{ item.totalQuantity }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 前厅 -->
          <el-tab-pane label="前厅" name="front">
            <div class="plan-list">
              <div v-if="planSummary.frontItems.length === 0" class="empty-plan">
                <el-empty description="暂无前厅菜品" />
              </div>
              <div v-else>
                <div
                  v-for="(item, index) in planSummary.frontItems"
                  :key="index"
                  class="plan-item"
                >
                  <div class="plan-item-rank">{{ index + 1 }}</div>
                  <div class="plan-item-info">
                    <span class="plan-item-name">{{ item.menuName }}</span>
                  </div>
                  <div class="plan-item-quantity">
                    <el-tag type="danger" size="large" effect="dark">
                      x{{ item.totalQuantity }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 后厨 -->
          <el-tab-pane label="后厨" name="kitchen">
            <div class="plan-list">
              <div v-if="planSummary.kitchenItems.length === 0" class="empty-plan">
                <el-empty description="暂无后厨菜品" />
              </div>
              <div v-else>
                <div
                  v-for="(item, index) in planSummary.kitchenItems"
                  :key="index"
                  class="plan-item"
                >
                  <div class="plan-item-rank">{{ index + 1 }}</div>
                  <div class="plan-item-info">
                    <span class="plan-item-name">{{ item.menuName }}</span>
                  </div>
                  <div class="plan-item-quantity">
                    <el-tag type="danger" size="large" effect="dark">
                      x{{ item.totalQuantity }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 吧台 -->
          <el-tab-pane label="吧台" name="bar">
            <div class="plan-list">
              <div v-if="planSummary.barItems.length === 0" class="empty-plan">
                <el-empty description="暂无吧台菜品" />
              </div>
              <div v-else>
                <div
                  v-for="(item, index) in planSummary.barItems"
                  :key="index"
                  class="plan-item"
                >
                  <div class="plan-item-rank">{{ index + 1 }}</div>
                  <div class="plan-item-info">
                    <span class="plan-item-name">{{ item.menuName }}</span>
                  </div>
                  <div class="plan-item-quantity">
                    <el-tag type="danger" size="large" effect="dark">
                      x{{ item.totalQuantity }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <el-button @click="planDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="printPlan">
          <el-icon><Printer /></el-icon>
          打印规划
        </el-button>
      </template>
    </el-dialog>

    <!-- 语音开启提示对话框 -->
    <el-dialog
      v-model="showVoicePrompt"
      width="420px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      center
      class="voice-prompt-dialog"
    >
      <template #header>
        <div class="voice-header">
          <el-icon class="voice-icon"><Microphone /></el-icon>
          <span class="voice-title">语音提示</span>
        </div>
      </template>
      <div class="voice-body">
        <p class="voice-message">检测到您首次使用出餐中心</p>
        <p class="voice-tip">是否开启新订单语音提醒？</p>
      </div>
      <template #footer>
        <div class="voice-footer">
          <el-button @click="skipVoice" class="skip-btn">暂不开启</el-button>
          <el-button type="primary" @click="enableVoice" class="enable-btn">
            <el-icon><Check /></el-icon>
            开启提醒
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Dish, Clock, Check, CircleCheck, Refresh, ArrowRight, DataAnalysis, Printer, Sort, Rank, View, Microphone } from '@element-plus/icons-vue'
import request from '@/utils/request.js'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()

// 所有订单数据
const allOrders = ref([])
// 展开的订单（最多4个）
const expandedOrderIds = ref([])
// 自动刷新定时器
let refreshTimer = null
// 上一次的订单数据（用于检测新订单和新增菜品）
// 格式：{ order_id: { table_number: '卡4', item_ids: Set([1, 2, 3]) } }
const previousOrdersData = ref(new Map())
// 快速规划对话框
const planDialogVisible = ref(false)
// 当前激活的标签页
const activeTab = ref('all')
// 按时间排序
const sortByTime = ref(false)
// 订单详情弹窗
const orderDialogVisible = ref(false)
// 当前弹窗显示的订单
const currentDialogOrderId = ref(null)
// 拖拽相关
const draggedIndex = ref(null)
// 语音提示对话框
const showVoicePrompt = ref(false)
// 语音是否已激活
const voiceEnabled = ref(false)

// 根据用户角色获取允许查看的餐品类型
const allowedCategoryTypes = computed(() => {
  const roles = userStore.roles

  // 管理员可以看所有类型
  if (roles.includes('admin')) {
    return ['前厅', '后厨', '吧台']
  }

  // 根据角色返回对应的餐品类型
  const typeMap = {
    'front_hall': ['前厅'],    // 前厅员工角色
    'kitchen': ['后厨'],       // 后厨员工角色
    'bar': ['吧台']            // 吧台员工角色
  }

  // 查找用户拥有的餐品类型权限
  const userTypes = []
  for (const role of roles) {
    if (typeMap[role]) {
      userTypes.push(...typeMap[role])
    }
  }

  // 如果没有匹配到特定角色，默认返回所有类型（兼容性处理）
  return userTypes.length > 0 ? userTypes : ['前厅', '后厨', '吧台']
})

// 排序后的订单列表
const sortedOrders = computed(() => {
  if (!sortByTime.value) {
    return allOrders.value
  }

  // 按首次下单时间排序（最早的在前，即等待时间最长的在前）
  return [...allOrders.value].sort((a, b) => {
    const timeA = new Date(a.first_item_time).getTime()
    const timeB = new Date(b.first_item_time).getTime()
    return timeA - timeB
  })
})

// 展开的订单列表
const expandedOrders = computed(() => {
  // 按照 expandedOrderIds 的顺序返回订单
  return expandedOrderIds.value
    .map(orderId => {
      const order = sortedOrders.value.find(o => o.order_id === orderId)
      if (order) {
        const items = parseItemsData(order.items_data)
        // 只返回有菜品的订单（过滤后可能没有菜品）
        if (items.length > 0) {
          return {
            ...order,
            items: items
          }
        }
      }
      return null
    })
    .filter(order => order !== null)
})

// 折叠的订单列表
const collapsedOrders = computed(() => {
  return sortedOrders.value
    .filter(order => !expandedOrderIds.value.includes(order.order_id))
    .filter(order => {
      // 只显示有权限查看的订单（至少有一个菜品属于当前角色）
      const items = parseItemsData(order.items_data)
      return items.length > 0
    })
})

// 当前弹窗显示的订单详情
const currentDialogOrder = computed(() => {
  if (!currentDialogOrderId.value) return null

  const order = sortedOrders.value.find(o => o.order_id === currentDialogOrderId.value)
  if (order) {
    const items = parseItemsData(order.items_data)
    // 只返回有权限查看的菜品
    if (items.length > 0) {
      return {
        ...order,
        items: items
      }
    }
  }
  return null
})

// 总订单数（只统计有权限查看的订单）
const totalOrders = computed(() => {
  return allOrders.value.filter(order => {
    const items = parseItemsData(order.items_data)
    return items.length > 0
  }).length
})

// 总待出餐菜品数（只统计当前角色有权限查看的菜品）
const totalItems = computed(() => {
  return allOrders.value.reduce((sum, order) => {
    const items = parseItemsData(order.items_data)
    return sum + items.length
  }, 0)
})

// 快速规划汇总数据
const planSummary = computed(() => {
  const summary = {
    totalItems: 0,
    allItems: [],
    frontItems: [],
    kitchenItems: [],
    barItems: []
  }

  // 如果没有展开的订单，返回空数据
  if (expandedOrders.value.length === 0) {
    return summary
  }

  // 用于汇总菜品的Map
  const menuMap = new Map()

  // 遍历所有展开的订单
  expandedOrders.value.forEach(order => {
    if (order.items && order.items.length > 0) {
      order.items.forEach(item => {
        const key = `${item.menu_name}_${item.category_type}`

        if (menuMap.has(key)) {
          // 如果已存在，累加数量
          const existing = menuMap.get(key)
          existing.totalQuantity += parseInt(item.quantity || 0)
        } else {
          // 如果不存在，创建新记录
          menuMap.set(key, {
            menuName: item.menu_name,
            categoryType: item.category_type,
            totalQuantity: parseInt(item.quantity || 0)
          })
        }
      })
    }
  })

  // 将Map转换为数组并按数量排序
  const allItems = Array.from(menuMap.values()).sort((a, b) => b.totalQuantity - a.totalQuantity)

  // 计算总项数
  summary.totalItems = allItems.reduce((sum, item) => sum + item.totalQuantity, 0)

  // 全部菜品
  summary.allItems = allItems

  // 按类型分组
  summary.frontItems = allItems.filter(item => item.categoryType === '前厅').sort((a, b) => b.totalQuantity - a.totalQuantity)
  summary.kitchenItems = allItems.filter(item => item.categoryType === '后厨').sort((a, b) => b.totalQuantity - a.totalQuantity)
  summary.barItems = allItems.filter(item => item.categoryType === '吧台').sort((a, b) => b.totalQuantity - a.totalQuantity)

  return summary
})

// 解析菜品数据（从GROUP_CONCAT的字符串中解析，并根据角色权限过滤）
function parseItemsData(itemsData) {
  if (!itemsData) return []

  const items = []
  const itemStrings = itemsData.split(';;')
  const allowedTypes = allowedCategoryTypes.value

  for (const itemStr of itemStrings) {
    const parts = itemStr.split('|')
    if (parts.length >= 5) {
      const categoryType = parts[3]

      // 只添加当前角色有权限查看的菜品
      if (allowedTypes.includes(categoryType)) {
        items.push({
          id: parts[0],
          menu_name: parts[1],
          quantity: parts[2],
          category_type: categoryType,
          create_time: parts[4]
        })
      }
    }
  }

  return items
}

// 获取餐品类型颜色
function getCategoryTypeColor(categoryType) {
  const colorMap = {
    '前厅': 'success',
    '后厨': 'primary',
    '吧台': 'warning'
  }
  return colorMap[categoryType] || 'info'
}

// 获取待出餐订单
function getPendingOrders() {
  request({
    url: '/restaurant/order/kitchen/pending-by-order',
    method: 'get',
    params: {
      categoryTypes: allowedCategoryTypes.value
    }
  }).then(response => {
    const orders = response.data || []

    // 过滤出有权限查看的订单（至少有一个菜品属于当前角色）
    const validOrders = orders.filter(order => {
      const items = parseItemsData(order.items_data)
      return items.length > 0
    })

    // 检测新订单和新增菜品（只在有历史数据时检测）
    if (previousOrdersData.value.size > 0) {
      const notifications = [] // 存储所有需要播放的语音提示

      validOrders.forEach(order => {
        const orderId = order.order_id
        const tableNumber = order.table_number
        const items = parseItemsData(order.items_data)
        const currentItemIds = new Set(items.map(item => item.id))

        // 检查是否是新订单
        if (!previousOrdersData.value.has(orderId)) {
          console.log(`检测到新订单: ${tableNumber} (订单ID: ${orderId})`)
          notifications.push(`${tableNumber}新订单请注意查收`)
        } else {
          // 检查是否有新增菜品
          const previousItemIds = previousOrdersData.value.get(orderId).item_ids
          const newItemIds = [...currentItemIds].filter(id => !previousItemIds.has(id))

          if (newItemIds.length > 0) {
            console.log(`检测到${tableNumber}新增菜品: ${newItemIds.length}个`)
            notifications.push(`${tableNumber}新增菜品请注意查收`)
          }
        }
      })

      // 播放语音提示
      if (notifications.length > 0) {
        console.log('=== 语音提示列表 ===')
        console.log(notifications)

        // 播放所有提示（用逗号分隔）
        const message = notifications.join('，')
        playVoiceNotification(message)
        ElMessage.success(`检测到 ${notifications.length} 个更新`)
      }
    }

    // 更新订单数据（保存订单ID、餐台号和菜品ID列表）
    const newOrdersData = new Map()
    validOrders.forEach(order => {
      const items = parseItemsData(order.items_data)
      newOrdersData.set(order.order_id, {
        table_number: order.table_number,
        item_ids: new Set(items.map(item => item.id))
      })
    })
    previousOrdersData.value = newOrdersData

    allOrders.value = orders

    // 使用排序后的订单列表
    const ordersToUse = sortByTime.value
      ? [...orders].sort((a, b) => {
          const timeA = new Date(a.first_item_time).getTime()
          const timeB = new Date(b.first_item_time).getTime()
          return timeA - timeB
        })
      : orders

    // 默认展开前4个订单
    if (expandedOrderIds.value.length === 0 && ordersToUse.length > 0) {
      expandedOrderIds.value = ordersToUse.slice(0, 4).map(o => o.order_id)
    } else {
      // 保留已展开的订单，移除已完成的订单
      const currentOrderIds = ordersToUse.map(o => o.order_id)
      expandedOrderIds.value = expandedOrderIds.value.filter(id => currentOrderIds.includes(id))

      // 如果展开的订单少于4个，自动补充
      if (expandedOrderIds.value.length < 4 && ordersToUse.length > expandedOrderIds.value.length) {
        const remainingOrders = ordersToUse.filter(o => !expandedOrderIds.value.includes(o.order_id))
        const needCount = Math.min(4 - expandedOrderIds.value.length, remainingOrders.length)
        expandedOrderIds.value.push(...remainingOrders.slice(0, needCount).map(o => o.order_id))
      }
    }
  }).catch(error => {
    ElMessage.error('获取待出餐订单失败')
  })
}

// 展开订单到卡片位置
function expandOrderToCard(orderId) {
  // 如果已经展开了4个订单，移除最早展开的一个
  if (expandedOrderIds.value.length >= 4) {
    expandedOrderIds.value.shift()
  }

  // 添加新展开的订单
  if (!expandedOrderIds.value.includes(orderId)) {
    expandedOrderIds.value.push(orderId)
  }
}

// 显示订单详情弹窗
function showOrderDialog(orderId) {
  currentDialogOrderId.value = orderId
  orderDialogVisible.value = true
}

// 从弹窗中展开订单到卡片
function expandOrderToCardFromDialog() {
  if (currentDialogOrderId.value) {
    expandOrderToCard(currentDialogOrderId.value)
    orderDialogVisible.value = false
  }
}

// 从弹窗中标记为已出餐
function markAsServedFromDialog(itemId) {
  markAsServed(itemId, currentDialogOrderId.value)
}

// 切换排序方式
function toggleSortByTime() {
  sortByTime.value = !sortByTime.value

  // 重新应用排序到所有订单
  if (allOrders.value.length > 0) {
    const sortedList = sortByTime.value
      ? [...allOrders.value].sort((a, b) => {
          const timeA = new Date(a.first_item_time).getTime()
          const timeB = new Date(b.first_item_time).getTime()
          return timeA - timeB
        })
      : allOrders.value

    // 展开排序后的前4个订单
    expandedOrderIds.value = sortedList.slice(0, 4).map(o => o.order_id)
  }

  ElMessage.success(sortByTime.value ? '已切换为时间排序（等待最久的4个订单）' : '已切换为默认排序（前4个订单）')
}

// 拖拽开始
function handleDragStart(index, event) {
  draggedIndex.value = index
  event.dataTransfer.effectAllowed = 'move'
  event.target.style.opacity = '0.5'
}

// 拖拽经过
function handleDragOver(index, event) {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
}

// 拖拽结束
function handleDragEnd(event) {
  event.target.style.opacity = '1'
  draggedIndex.value = null
}

// 放置
function handleDrop(targetIndex, event) {
  event.preventDefault()

  if (draggedIndex.value === null || draggedIndex.value === targetIndex) {
    return
  }

  // 交换两个订单的位置
  const newExpandedOrderIds = [...expandedOrderIds.value]
  const draggedOrderId = newExpandedOrderIds[draggedIndex.value]

  // 移除拖拽的订单
  newExpandedOrderIds.splice(draggedIndex.value, 1)
  // 插入到目标位置
  newExpandedOrderIds.splice(targetIndex, 0, draggedOrderId)

  expandedOrderIds.value = newExpandedOrderIds

  ElMessage.success('订单位置已调整')
}

// 标记为已出餐
function markAsServed(itemId, orderId) {
  request({
    url: `/restaurant/order/kitchen/serve/${itemId}`,
    method: 'put'
  }).then(response => {
    ElMessage.success('已标记为出餐')
    getPendingOrders()
  }).catch(error => {
    ElMessage.error('操作失败')
  })
}

// 刷新数据
function refreshData() {
  getPendingOrders()
  ElMessage.success('数据已刷新')
}

// 开启语音功能
function enableVoice() {
  console.log('=== 用户点击开启语音 ===')

  // 标记语音已激活
  voiceEnabled.value = true

  // 保存到 localStorage
  localStorage.setItem('kitchenVoiceEnabled', 'true')

  // 关闭提示对话框
  showVoicePrompt.value = false

  ElMessage.success('语音提醒已开启')
}

// 跳过语音功能
function skipVoice() {
  console.log('=== 用户选择暂不开启语音 ===')

  // 标记为已选择（避免下次再弹出）
  localStorage.setItem('kitchenVoiceEnabled', 'false')

  // 关闭提示对话框
  showVoicePrompt.value = false

  ElMessage.info('您可以稍后在设置中开启语音提醒')
}

// 显示快速规划对话框
function showQuickPlan() {
  if (expandedOrders.value.length === 0) {
    ElMessage.warning('当前没有展开的订单')
    return
  }

  planDialogVisible.value = true
  activeTab.value = 'all'
}

// 打印规划
function printPlan() {
  // 构建打印内容
  let printContent = `
    <html>
      <head>
        <title>快速规划 - 菜品汇总</title>
        <style>
          body {
            font-family: Arial, sans-serif;
            padding: 20px;
          }
          h1 {
            text-align: center;
            color: #333;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
          }
          .summary {
            background-color: #f0f2f5;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 16px;
            font-weight: 600;
          }
          .section {
            margin-bottom: 30px;
          }
          .section-title {
            font-size: 18px;
            font-weight: 600;
            color: #667eea;
            margin-bottom: 10px;
            border-left: 4px solid #667eea;
            padding-left: 10px;
          }
          table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
          }
          th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
          }
          th {
            background-color: #667eea;
            color: white;
            font-weight: 600;
          }
          tr:nth-child(even) {
            background-color: #f9fafb;
          }
          .quantity {
            font-weight: 600;
            color: #f56c6c;
            font-size: 16px;
          }
          .print-time {
            text-align: right;
            color: #909399;
            margin-top: 20px;
            font-size: 14px;
          }
        </style>
      </head>
      <body>
        <h1>快速规划 - 菜品汇总</h1>
        <div class="summary">
          当前展开 ${expandedOrders.value.length} 个订单，共需准备 ${planSummary.value.totalItems} 项菜品
        </div>
  `

  // 添加全部菜品
  if (planSummary.value.allItems.length > 0) {
    printContent += `
      <div class="section">
        <div class="section-title">全部菜品</div>
        <table>
          <thead>
            <tr>
              <th style="width: 60px;">序号</th>
              <th>菜品名称</th>
              <th style="width: 100px;">类型</th>
              <th style="width: 100px;">数量</th>
            </tr>
          </thead>
          <tbody>
    `
    planSummary.value.allItems.forEach((item, index) => {
      printContent += `
        <tr>
          <td>${index + 1}</td>
          <td>${item.menuName}</td>
          <td>${item.categoryType}</td>
          <td class="quantity">x${item.totalQuantity}</td>
        </tr>
      `
    })
    printContent += `
          </tbody>
        </table>
      </div>
    `
  }

  // 添加前厅菜品
  if (planSummary.value.frontItems.length > 0) {
    printContent += `
      <div class="section">
        <div class="section-title">前厅菜品</div>
        <table>
          <thead>
            <tr>
              <th style="width: 60px;">序号</th>
              <th>菜品名称</th>
              <th style="width: 100px;">数量</th>
            </tr>
          </thead>
          <tbody>
    `
    planSummary.value.frontItems.forEach((item, index) => {
      printContent += `
        <tr>
          <td>${index + 1}</td>
          <td>${item.menuName}</td>
          <td class="quantity">x${item.totalQuantity}</td>
        </tr>
      `
    })
    printContent += `
          </tbody>
        </table>
      </div>
    `
  }

  // 添加后厨菜品
  if (planSummary.value.kitchenItems.length > 0) {
    printContent += `
      <div class="section">
        <div class="section-title">后厨菜品</div>
        <table>
          <thead>
            <tr>
              <th style="width: 60px;">序号</th>
              <th>菜品名称</th>
              <th style="width: 100px;">数量</th>
            </tr>
          </thead>
          <tbody>
    `
    planSummary.value.kitchenItems.forEach((item, index) => {
      printContent += `
        <tr>
          <td>${index + 1}</td>
          <td>${item.menuName}</td>
          <td class="quantity">x${item.totalQuantity}</td>
        </tr>
      `
    })
    printContent += `
          </tbody>
        </table>
      </div>
    `
  }

  // 添加吧台菜品
  if (planSummary.value.barItems.length > 0) {
    printContent += `
      <div class="section">
        <div class="section-title">吧台菜品</div>
        <table>
          <thead>
            <tr>
              <th style="width: 60px;">序号</th>
              <th>菜品名称</th>
              <th style="width: 100px;">数量</th>
            </tr>
          </thead>
          <tbody>
    `
    planSummary.value.barItems.forEach((item, index) => {
      printContent += `
        <tr>
          <td>${index + 1}</td>
          <td>${item.menuName}</td>
          <td class="quantity">x${item.totalQuantity}</td>
        </tr>
      `
    })
    printContent += `
          </tbody>
        </table>
      </div>
    `
  }

  // 添加打印时间
  const now = new Date()
  const printTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`

  printContent += `
        <div class="print-time">打印时间：${printTime}</div>
      </body>
    </html>
  `

  // 打开新窗口并打印
  const printWindow = window.open('', '_blank')
  printWindow.document.write(printContent)
  printWindow.document.close()
  printWindow.focus()

  // 延迟打印，确保内容加载完成
  setTimeout(() => {
    printWindow.print()
  }, 250)

  ElMessage.success('正在准备打印...')
}

// 格式化时间（只显示分钟）
function formatTimeInMinutes(time) {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  const minutes = Math.floor(diff / 60000)

  if (minutes < 1) return '1分钟'
  return `${minutes}分钟`
}

// 格式化时间
function formatTime(time) {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  const minutes = Math.floor(diff / 60000)

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`

  const hours = date.getHours().toString().padStart(2, '0')
  const mins = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${mins}`
}

// 格式化完整时间
function formatFullTime(time) {
  if (!time) return ''
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const mins = String(date.getMinutes()).padStart(2, '0')
  const secs = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${mins}:${secs}`
}

// 播放语音提示
function playVoiceNotification(text) {
  console.log('=== 尝试播放语音 ===')
  console.log('语音内容:', text)

  // 检查浏览器是否支持语音合成API
  if (!('speechSynthesis' in window)) {
    console.error('浏览器不支持语音合成API')
    ElMessage.warning('您的浏览器不支持语音提示功能')
    return
  }

  try {
    // 取消之前的语音（如果有）
    window.speechSynthesis.cancel()

    const utterance = new SpeechSynthesisUtterance(text)
    utterance.lang = 'zh-CN' // 设置为中文
    utterance.rate = 1.0 // 语速
    utterance.pitch = 1.0 // 音调
    utterance.volume = 1.0 // 音量

    // 添加事件监听器用于调试
    utterance.onstart = () => {
      console.log('语音开始播放')
    }

    utterance.onend = () => {
      console.log('语音播放完成')
    }

    utterance.onerror = (event) => {
      console.error('语音播放错误:', event)
      console.error('错误类型:', event.error)
    }

    console.log('调用 speechSynthesis.speak()')
    window.speechSynthesis.speak(utterance)

    // 检查语音是否正在播放
    setTimeout(() => {
      console.log('speechSynthesis.speaking:', window.speechSynthesis.speaking)
      console.log('speechSynthesis.pending:', window.speechSynthesis.pending)
      console.log('speechSynthesis.paused:', window.speechSynthesis.paused)
    }, 100)
  } catch (error) {
    console.error('播放语音时发生异常:', error)
    ElMessage.error('语音播放失败')
  }
}

onMounted(() => {
  // 检查是否已经选择过语音设置
  const voiceEnabledStatus = localStorage.getItem('kitchenVoiceEnabled')

  if (voiceEnabledStatus === 'true') {
    // 已经开启过语音，直接标记为已激活
    voiceEnabled.value = true
  } else if (voiceEnabledStatus === null) {
    // 首次进入（没有任何记录），显示语音开启提示
    // 延迟500ms显示，让页面先加载完成
    setTimeout(() => {
      showVoicePrompt.value = true
    }, 500)
  }
  // 如果是 'false'，说明用户选择了暂不开启，不再弹出提示

  getPendingOrders()

  // 每5秒自动刷新并检测新订单
  refreshTimer = setInterval(() => {
    getPendingOrders()
  }, 5000)
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>


<style lang="scss" scoped>
.kitchen-center-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  color: white;
  position: relative;

  .header-icon {
    font-size: 32px;
    margin-right: 15px;
  }

  .header-title {
    font-size: 28px;
    font-weight: 600;
    margin: 0;
    flex-shrink: 0;
  }

  .header-info {
    margin-left: 30px;
    display: flex;
    align-items: center;
    flex: 1;
  }

  .header-actions {
    margin-left: auto;
    display: flex;
    align-items: center;
    gap: 10px;

    .plan-btn,
    .sort-btn {
      background-color: rgba(255, 255, 255, 0.2);
      border: 1px solid rgba(255, 255, 255, 0.3);
      color: white;
      font-weight: 500;

      &:hover:not(:disabled) {
        background-color: rgba(255, 255, 255, 0.3);
        border-color: rgba(255, 255, 255, 0.5);
      }

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }

    .refresh-btn {
      background-color: rgba(255, 255, 255, 0.2);
      border: none;
      color: white;

      &:hover {
        background-color: rgba(255, 255, 255, 0.3);
      }
    }
  }
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #909399;

  .empty-icon {
    font-size: 80px;
    margin-bottom: 20px;
    opacity: 0.5;
  }

  p {
    font-size: 18px;
    margin: 0;
  }
}

// 展开的订单卡片
.expanded-orders-section {
  margin-bottom: 30px;
}

// 可拖拽的列
.draggable-col {
  cursor: move;
  transition: all 0.3s ease;

  &:active {
    cursor: grabbing;
  }
}

.order-card {
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-card__header) {
    padding: 15px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-bottom: none;
  }

  :deep(.el-card__body) {
    padding: 15px;
  }
}

.order-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;

  .order-info {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
    min-width: 0;

    .order-number {
      font-size: 15px;
      font-weight: 600;
      color: white;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .order-meta {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 13px;
    color: rgba(255, 255, 255, 0.9);
    white-space: nowrap;
    flex-shrink: 0;

    .el-icon {
      font-size: 14px;
    }
  }
}

.order-items {
  max-height: 400px;
  overflow-y: auto;
}

.menu-item {
  padding: 12px;
  background-color: #f9fafb;
  border-radius: 8px;
  margin-bottom: 10px;
  transition: all 0.2s ease;

  &:last-child {
    margin-bottom: 0;
  }

  &:hover {
    background-color: #f0f2f5;
    transform: translateX(5px);
  }

  .menu-item-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    flex-wrap: wrap;

    .menu-name {
      font-size: 15px;
      font-weight: 500;
      color: #303133;
      flex: 1;
      min-width: 100px;
    }
  }

  .menu-item-time {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 13px;
    color: #909399;
    margin-bottom: 10px;

    .el-icon {
      font-size: 14px;
    }
  }

  .serve-btn {
    width: 100%;
  }
}

// 折叠的订单列表
.collapsed-orders-section {
  margin-top: 40px;

  .divider-text {
    font-size: 16px;
    font-weight: 500;
    color: #606266;
  }
}

.collapsed-orders-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-top: 20px;
}

.collapsed-order-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background-color: white;
  border-radius: 8px;
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;

  &:hover {
    border-color: #667eea;
    background-color: #f5f7ff;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
  }

  .collapsed-order-info {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
    flex-wrap: wrap;
    cursor: pointer;

    &:hover {
      .order-number {
        color: #667eea;
      }
    }

    .order-number {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      transition: color 0.2s ease;
    }
  }

  .collapsed-order-time {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 13px;
    color: #909399;
    margin-right: 15px;

    .el-icon {
      font-size: 14px;
    }
  }

  .collapsed-order-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

// 订单详情弹窗样式
.order-dialog-content {
  .order-dialog-header {
    margin-bottom: 20px;
  }

  .order-dialog-items {
    max-height: 400px;
    overflow-y: auto;
  }

  .dialog-menu-item {
    padding: 12px;
    background-color: #f9fafb;
    border-radius: 8px;
    margin-bottom: 10px;
    transition: all 0.2s ease;

    &:last-child {
      margin-bottom: 0;
    }

    &:hover {
      background-color: #f0f2f5;
      transform: translateX(5px);
    }

    .dialog-menu-item-info {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
      flex-wrap: wrap;

      .dialog-menu-name {
        font-size: 15px;
        font-weight: 500;
        color: #303133;
        flex: 1;
        min-width: 100px;
      }
    }

    .dialog-menu-item-time {
      display: flex;
      align-items: center;
      gap: 5px;
      font-size: 13px;
      color: #909399;
      margin-bottom: 10px;

      .el-icon {
        font-size: 14px;
      }
    }

    .dialog-serve-btn {
      width: 100%;
    }
  }
}

// 快速规划对话框样式
.plan-dialog-content {
  .plan-summary {
    margin-bottom: 20px;
  }

  .plan-tabs {
    :deep(.el-tabs__header) {
      margin-bottom: 20px;
    }

    :deep(.el-tabs__item) {
      font-size: 15px;
      font-weight: 500;
    }
  }

  .plan-list {
    max-height: 500px;
    overflow-y: auto;
    padding: 10px;
  }

  .empty-plan {
    padding: 40px 0;
  }

  .plan-item {
    display: flex;
    align-items: center;
    padding: 15px;
    background-color: #f9fafb;
    border-radius: 8px;
    margin-bottom: 12px;
    transition: all 0.2s ease;

    &:hover {
      background-color: #f0f2f5;
      transform: translateX(5px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .plan-item-rank {
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 50%;
      font-size: 16px;
      font-weight: 600;
      margin-right: 15px;
      flex-shrink: 0;
    }

    .plan-item-info {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 10px;

      .plan-item-name {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }

    .plan-item-quantity {
      margin-left: 15px;
      flex-shrink: 0;
    }
  }
}

// 响应式布局
@media (max-width: 1200px) {
  .order-card {
    :deep(.el-col-lg-6) {
      max-width: 50%;
      flex: 0 0 50%;
    }
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-wrap: wrap;

    .header-info {
      margin-left: 0;
      margin-top: 15px;
      width: 100%;
    }

    .refresh-btn {
      position: absolute;
      top: 20px;
      right: 20px;
    }
  }

  .collapsed-orders-list {
    grid-template-columns: 1fr;
  }
}

/* 语音提示对话框样式 */
.voice-prompt-dialog {
  :deep(.el-dialog) {
    border-radius: 16px;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  }

  :deep(.el-dialog__header) {
    padding: 24px 24px 16px;
    border-bottom: 1px solid #f0f0f0;
  }

  :deep(.el-dialog__body) {
    padding: 24px;
  }

  :deep(.el-dialog__footer) {
    padding: 16px 24px 24px;
    border-top: 1px solid #f0f0f0;
  }

  .voice-header {
    display: flex;
    align-items: center;
    gap: 12px;

    .voice-icon {
      font-size: 28px;
      color: #409eff;
    }

    .voice-title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .voice-body {
    text-align: center;
    padding: 10px 0;

    .voice-message {
      font-size: 15px;
      color: #606266;
      margin-bottom: 8px;
      line-height: 1.6;
    }

    .voice-tip {
      font-size: 14px;
      color: #909399;
      margin: 0;
    }
  }

  .voice-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .skip-btn {
      padding: 9px 20px;
      font-size: 14px;
      color: #606266;
      border-color: #dcdfe6;

      &:hover {
        color: #409eff;
        border-color: #c6e2ff;
        background-color: #ecf5ff;
      }
    }

    .enable-btn {
      padding: 9px 24px;
      font-size: 14px;
      font-weight: 500;
      background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
      }
    }
  }
}
</style>
